package com.jgy.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jgy.annotation.RequestLimit;
import com.jgy.annotation.SetLogValue;
import com.jgy.client.FileClient;
import com.jgy.entity.FOrder;
import com.jgy.entity.Goods;
import com.jgy.entity.SpaceUser;
import com.jgy.entity.vo.GoodsVo;
import com.jgy.handler.LightException;
import com.jgy.mapper.FOrderMapper;
import com.jgy.mapper.GoodsMapper;
import com.jgy.rabbit.DeadLetterQueueConfig;
import com.jgy.service.GoodsService;
import com.jgy.utils.CommonConstants;
import com.jgy.utils.DateUtil;
import com.jgy.utils.R;
import com.jgy.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author 姜光远
 * @date 2023/4/1 16:37
 */
@Slf4j
@RestController
@RequestMapping("/shop")
public class OrderController {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FOrderMapper fOrderMapper;



    @Resource
    private RabbitTemplate rabbitTemplate;

    @SetLogValue(modular = "文件上传",type = CommonConstants.SELECT, describe = "oss文件上传")
    @PostMapping("uploadFile")
    @DS("master")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        return goodsService.uploadFile(file);
    }

    @SetLogValue(modular = "商品模块",type = CommonConstants.SELECT, describe = "查询商品")
    @GetMapping("/getList")
    public R<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10") Integer pageSize,
                         @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Goods> wrapper = Wrappers.<Goods>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Goods::getGoods, search);
        }
        Page<Goods> bookPage = goodsMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return R.ok(bookPage);
    }

    @SetLogValue(modular = "111111",type = CommonConstants.SELECT, describe = "111111")
    @GetMapping("/testList")
    public R<?> findPages(@RequestParam(defaultValue = "") String search) {
        List<Goods> goodsList = goodsMapper.likeSelect(search);
        return R.ok(goodsList.size());
    }

    /**
     * 下单购买操作
     * @param id 商品id
     * @return 是否下单成功
     * @throws InterruptedException 睡眠3s，模仿网络波动
     */
    @SetLogValue(modular = "商品模块",type = CommonConstants.ADD, describe = "购买商品")
    @GetMapping("/bugGoods")
    @RequestLimit(enable = true)
    public R<?> bugGoods(@RequestParam Integer id) throws InterruptedException {
        log.info("接口开始睡眠！");
        Thread.sleep(1000);
        log.info("一秒睡眠结束！");
        Goods goods = goodsMapper.selectById(id);
        //当前用户登录信息
        SpaceUser user = SecurityUtil.getUser();
        String uuid = StrUtil.uuid();
        FOrder order = FOrder.builder()
                .createTime(new Date())
                .orderNo(uuid)
                .payableFee(goods.getPrice())
                .payState(0)  // 0 是未支付 1是已支付 2是下单后取消
                .title(goods.getGoods())
                .productId(goods.getId().toString())
                .userId(user.getUsername())
                .build();
        int res = fOrderMapper.insert(order);

        rabbitTemplate.convertAndSend(DeadLetterQueueConfig.DEAD_LETTER_EXCHANGE, DeadLetterQueueConfig.DEAD_LETTER_ROUTING_KEY,uuid);
        log.info("当前时间:{} 下单订单号:{}", DateUtil.getCuurentDateStr(),uuid);
        return res>0? R.ok().setMsg("下单成功") : R.failed().setMsg("下单失败，请联系管理员！");
    }



    @SetLogValue(modular = "订单模块",type = CommonConstants.SELECT, describe = "查询订单")
    @GetMapping("/getOrderList")
    public R<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10") Integer pageSize,
                         @RequestParam(defaultValue = "") String search,
                         @RequestParam String mdosName) {
        LambdaQueryWrapper<FOrder> wrapper = Wrappers.<FOrder>lambdaQuery();
        wrapper.eq(FOrder::getUserId,mdosName);
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(FOrder::getTitle, search);
        }
        Page<FOrder> bookPage = fOrderMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return R.ok(bookPage);
    }

    //支付操作
    @SetLogValue(modular = "商品模块",type = CommonConstants.UPDATE, describe = "支付操作")
    @GetMapping("/pay")
    public R<?> pay(@RequestParam String id){
        int res = fOrderMapper.eidt(id);
        return res>0? R.ok("支付成功") : R.failed("支付失败，请联系管理员！");
    }
    @SetLogValue(modular = "商品模块",type = CommonConstants.SELECT, describe = "查询单条记录")
    //查询单条记录
    @GetMapping("/getById")
    public R<?> getById(@RequestParam String id) {
        FOrder fOrder = fOrderMapper.selectById(id);
        return R.ok(fOrder);
    }
    @SetLogValue(modular = "商品模块",type = CommonConstants.DELETE, describe = "删除商品")
    @DeleteMapping("/deleteById")
    public R<?> deleteById(@RequestParam(value = "id") String id) {
        int i = fOrderMapper.deleteById(id);
        return i>0?R.ok("删除成功"):R.failed("删除失败，请联系管理员！");
    }

    @SetLogValue(modular = "商品模块",type = CommonConstants.EXPORT,describe = "导出商品excel")
    @PostMapping("/exportGoods")
    public void exportGoods(@RequestBody GoodsVo goodsVo, HttpServletResponse response){
        try {
            goodsService.exportGoods(goodsVo,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SetLogValue(modular = "商品模块",type = CommonConstants.EXPORT,describe = "导出商品word")
    @PostMapping("/wordGoods")
    public void wordGoods( HttpServletResponse response){
        try {
            goodsService.wordGoods(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SetLogValue(modular = "商品模块",type = CommonConstants.EXPORT,describe = "新增商品")
    @PostMapping("/addGoods")
    public R addGoods( @RequestBody Goods goods){
        int insert = goodsMapper.insert(goods);
        return insert>0?R.ok(): R.failed();
    }
}
